package cn.doitedu.api;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class _01_WorldCount {

    public static void main(String[] args) throws Exception {

        // 首先，构造一个编程环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        // 添加数据源，映射成 dataStream
        // 需要在目标机器上，用这个命令去绑定指定的端口来提供数据：  hunter@hitao:~$ nc -lk 8899
        DataStreamSource<String> stream = env.socketTextStream("localhost", 8899);

        // word,count,spark 变大写
        SingleOutputStreamOperator<String> mapped = stream.map(new ToUpperMapper());

        // 单词切割  WORD,COUNT,SPARK,FLINK
        SingleOutputStreamOperator<String> flatMapped = mapped.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {

                String[] split = value.split(",");
                for (String w : split) {
                    out.collect(w);
                }

            }
        });

        // 将单词变成   (单词,1) :  w -> (w,1)
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = flatMapped.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String word) throws Exception {
                return Tuple2.of(word, 1);
            }
        });


        // 分组聚合
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordAndCount.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {

                return value.f0;
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> resultStream = keyedStream.sum("f1");



        // 打印读到的数据
        resultStream.print();


        // 提交任务执行
        env.execute();


    }

}


class ToUpperMapper implements MapFunction<String, String> {

    @Override
    public String map(String value) throws Exception {
        return value.toUpperCase();
    }
}


